package com.linkhub.oms.dao.mpservice.impl;

import com.linkhub.oms.common.spring.QtApplicationContextHelper;
import com.linkhub.oms.common.util.json.QtFastjsonUtil;
import com.linkhub.oms.entity.DuplicatedRecordEntity;
import com.linkhub.oms.dao.mapper.DuplicatedRecordEntityMapper;
import com.linkhub.oms.dao.mpservice.IDuplicatedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xieyu
 * @since 2024-07-02
 */
@Slf4j
@Service
public class DuplicatedRecordServiceImpl extends ServiceImpl<DuplicatedRecordEntityMapper, DuplicatedRecordEntity> implements IDuplicatedRecordService {

    public boolean duplicated(String bizType, String bizNo, Object data) {
        return duplicated(bizType, bizNo, QtFastjsonUtil.toJSONString(data));
    }

    public boolean duplicated(String bizType, String bizNo, String data) {
        DuplicatedRecordEntity duplicatedRecordEntity = new DuplicatedRecordEntity();
        duplicatedRecordEntity.setType(bizType);
        duplicatedRecordEntity.setNo(bizNo);
        duplicatedRecordEntity.setData(data);
        try {
            return !save(duplicatedRecordEntity);
        } catch (DuplicateKeyException duplicateKeyException) {
            log.error("重复的业务操作，bizType: {}, bizNo: {}, data: {}", bizType, bizNo, data);
            return true;
        }
    }

    public void finished(String bizType, String bizNo) {
        lambdaUpdate()
                .eq(DuplicatedRecordEntity::getType, bizType)
                .eq(DuplicatedRecordEntity::getNo, bizNo)
                .set(DuplicatedRecordEntity::getStatus, 1)
                .update();
    }

    @Override
    public List<DuplicatedRecordEntity> listUnfinished() {
        return lambdaQuery().eq(DuplicatedRecordEntity::getStatus, 0).list();
    }
}
